package com.xinli.xinlifm.view.activity.player;

import android.content.ComponentName;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;
import com.xinli.xinlifm.R;
import com.xinli.xinlifm.http.bean.player.Mp3Info;
import com.xinli.xinlifm.http.bean.player.PlayerBean;
import com.xinli.xinlifm.mvp.model.SuperModel;
import com.xinli.xinlifm.utils.ConstantValue;
import com.xinli.xinlifm.view.broadcast.MusicBroadcast;
import com.xinli.xinlifm.view.service.IService;
import com.xinli.xinlifm.view.service.MusicService;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by zz on 16-10-14.
 */

public class PlayerActivity extends AppCompatActivity implements View.OnClickListener, SeekBar.OnSeekBarChangeListener ,Handler.Callback{
    private IService iService;
    private MusicServiceConnection connection;
    private ImageView titleImg;
    private TextView titleText;
    private TextView shouTinText;
    private ImageView pre;
    private ImageView play;
    private ImageView next;
    private TextView duration;
    private SeekBar seekbar;
    private CircleImageView circleImgUser;
    private TextView userName;
    private TextView introduce;
    private Button myMessage;
    private LinearLayout playerTab1;
    private LinearLayout playerTab2;
    private LinearLayout playerTab3;
    private LinearLayout playerTab4;
    private LinearLayout playerTab5;
    private ImageView fmLike;
    private TextView fmText;
    private ImageView playerBack;


    private Handler handler = new Handler(this);
    private ImageView pause;
    private MusicBroadcast musicBroadcast;
    private CircleImageView circleTitleImage;
    private Animation animation;

    private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss",Locale.CHINA);
    private MediaPlayer mediaPlayer;
    private String webTitle;
    private String webId;
    private String intExtra;
    private ImageView defaultImage;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_player);
        Intent data = getIntent();
        intExtra = data.getStringExtra("id");
        Log.e("自定义标签", "类名==PlayerActivity" + "方法名==onCreate=====:" + intExtra);
        musicBroadcast = new MusicBroadcast(handler);
        IntentFilter intentFilter = new IntentFilter("seekBar.length");
        registerReceiver(musicBroadcast,intentFilter);
        Intent intent = new Intent(this, MusicService.class);
        startService(intent);
        connection = new MusicServiceConnection();
        bindService(intent, connection, BIND_AUTO_CREATE);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        new SuperModel().getPlayer(Integer.parseInt(intExtra));
        initView();
        initEvent();
    }

    @Subscribe
    public void getMp3Status(Mp3Info mp3Info){
        int mpSeek = mp3Info.getLength();
        String mpTime = mp3Info.getTime();
        int max = mp3Info.getMax();
        seekbar.setMax(max);
//        seekbar.setProgress(mpSeek);
//        duration.setText(mpTime);
        play.setVisibility(View.INVISIBLE);
        pause.setVisibility(View.VISIBLE);
//        iService.putAcSeekBar(seekbar);

    }

    @Subscribe
    public void getMediaPlayer(MediaPlayer mediaPlayer){
        this.mediaPlayer = mediaPlayer;
        if(mediaPlayer.isPlaying()){
            handler.sendEmptyMessage(ConstantValue.START);
            play.setVisibility(View.INVISIBLE);
            pause.setVisibility(View.VISIBLE);
        }
        Log.e("自定义标签", "类名==PlayerActivity" + "方法名==getMediaPlayer=====:" + mediaPlayer+"---"+mediaPlayer.isPlaying());
    }
    @Subscribe
    public void getTheData(PlayerBean playerBean){
        PlayerBean.DataBean data = playerBean.getData();
        PlayerBean.DataBean.DiantaiBean diantai = data.getDiantai();
        PlayerBean.DataBean.DiantaiBean.UserBean user = diantai.getUser();
        titleText.setText(data.getTitle());
        Picasso.with(this).load(data.getCover()).placeholder(R.mipmap.default_1).resize(defaultImage.getMeasuredWidth(),defaultImage.getMeasuredHeight()).into(titleImg);
        Picasso.with(this).load(data.getCover()).placeholder(R.mipmap.default_1).resize(defaultImage.getMeasuredWidth(),defaultImage.getMeasuredHeight()).into(circleTitleImage);
        shouTinText.setText(data.getViewnum());
        Picasso.with(this).load(data.getCover()).placeholder(R.mipmap.cover_default).into(circleImgUser);
        userName.setText(user.getNickname());
        introduce.setText(diantai.getContent());
        Log.e("自定义标签", "类名==PlayerActivity" + "方法名==getData=====:" + "");
        webTitle = data.getTitle();
        webId = String.valueOf(data.getId());
    }

    private void initEvent() {
        titleImg.setOnClickListener(this);
        circleTitleImage.setOnClickListener(this);
        playerBack.setOnClickListener(this);
        titleText.setOnClickListener(this);
        shouTinText.setOnClickListener(this);
        pre.setOnClickListener(this);
        play.setOnClickListener(this);
        pause.setOnClickListener(this);
        next.setOnClickListener(this);
        circleImgUser.setOnClickListener(this);
        myMessage.setOnClickListener(this);
        playerTab1.setOnClickListener(this);
        playerTab2.setOnClickListener(this);
        playerTab3.setOnClickListener(this);
        playerTab4.setOnClickListener(this);
        playerTab5.setOnClickListener(this);
        seekbar.setOnSeekBarChangeListener(this);
    }

    private void initView() {
        defaultImage = (ImageView) findViewById(R.id.player_default_image);
        titleImg = (ImageView) findViewById(R.id.player_title_img);
        circleTitleImage = (CircleImageView) findViewById(R.id.player_title_circle_img);
        playerBack = (ImageView) findViewById(R.id.player_back);
        titleText = (TextView) findViewById(R.id.player_title_text);
        shouTinText = (TextView) findViewById(R.id.player_shou_tin_text);
        pre = (ImageView) findViewById(R.id.player_pre);
        play = (ImageView) findViewById(R.id.player_play);
        pause = (ImageView) findViewById(R.id.player_pause);
        next = (ImageView) findViewById(R.id.player_next);
        duration = (TextView) findViewById(R.id.player_duration);
        seekbar = (SeekBar) findViewById(R.id.payer_seekbar);
        circleImgUser = (CircleImageView) findViewById(R.id.player_circle_img);
        userName = (TextView) findViewById(R.id.player_user_name);
        introduce = (TextView) findViewById(R.id.player_introduce);
        myMessage = (Button) findViewById(R.id.player_my_message);
        playerTab1 = (LinearLayout) findViewById(R.id.player_ll_tab1);
        playerTab2 = (LinearLayout) findViewById(R.id.player_ll_tab2);
        playerTab3 = (LinearLayout) findViewById(R.id.player_ll_tab3);
        playerTab4 = (LinearLayout) findViewById(R.id.player_ll_tab4);
        playerTab5 = (LinearLayout) findViewById(R.id.player_ll_tab5);
        //////////////////////////////////////
        fmLike = (ImageView) findViewById(R.id.player_fm_like);
        fmText = (TextView) findViewById(R.id.fm_like_text);

    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.e("自定义标签", "类名==PlayerActivity" + "方法名==onResume=====:" + mediaPlayer);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                iService.putAcSeekBar(seekbar);
                animation = AnimationUtils.loadAnimation(PlayerActivity.this, R.anim.player_circle_img);
                animation.setInterpolator(new LinearInterpolator());
                if (circleTitleImage.getAnimation() == null) {
                    circleTitleImage.startAnimation(animation);
                }
            }
        },300);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(connection);
        EventBus.getDefault().unregister(this);
        unregisterReceiver(musicBroadcast);

    }
    public static boolean isPlay =false;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.player_play:  //开起
                    if(isPlay){
                        iService.callStartMusic();
                    }else {
                        //// TODO: 16-10-15
                        //传个position过去
                        iService.callPlayMusic(Integer.parseInt(intExtra));
                        duration.setText("缓存中...");
                        seekbar.setProgress(0);
                    }
                    isPlay=true;
                    play.setVisibility(View.INVISIBLE);
                    pause.setVisibility(View.VISIBLE);
                //设置动画
                if (circleTitleImage.getAnimation() == null) {
                    circleTitleImage.startAnimation(animation);
                }

                break;
            case R.id.player_pause:  //暂停
                    iService.callPauseMusic();
                    play.setVisibility(View.VISIBLE);
                    pause.setVisibility(View.INVISIBLE);
                    handler.removeMessages(ConstantValue.seek_auto_update);
                    if (circleTitleImage.getAnimation() != null) {
                        circleTitleImage.clearAnimation();
                    }

                break;
            case R.id.player_next:  //上下首都不写了
                    handler.removeMessages(ConstantValue.seek_auto_update);
//                    iService.callNextMusic();
//                    seekbar.setProgress(0);
                    duration.setText("缓存中...");

                break;
            case R.id.player_pre:   //上下首都不写了
                    handler.removeMessages(ConstantValue.seek_auto_update);
//                    iService.callPreMusic();
//                    seekbar.setProgress(0);
                    duration.setText("缓存中...");
                break;

            case R.id.player_ll_tab5:
//                Toast.makeText(this, "11111", Toast.LENGTH_SHORT).show();
                View view = LayoutInflater.from(this).inflate(R.layout.popup_more_item, null);
                LinearLayout moreDownload = (LinearLayout)view.findViewById(R.id.more_download);
                LinearLayout moreRead = (LinearLayout)view.findViewById(R.id.more_read);


                final PopupWindow popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
                popupWindow.setFocusable(true);
                popupWindow.setOutsideTouchable(true);
                float x = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 15, getResources().getDisplayMetrics());
                float y = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 55, getResources().getDisplayMetrics());
                popupWindow.showAtLocation(playerTab5, Gravity.BOTTOM|Gravity.RIGHT, (int)x, (int)y);

                moreDownload.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(PlayerActivity.this, "下载", Toast.LENGTH_SHORT).show();
                        popupWindow.dismiss();
                    }
                });

                moreRead.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(PlayerActivity.this,MoreActivity.class);
                        intent.putExtra("ids",webId);
                        intent.putExtra("title",webTitle);
                        PlayerActivity.this.startActivity(intent);
                        Log.e("自定义标签", "类名==PlayerActivity" + "方法名==onClick=====:" + webId);
                        popupWindow.dismiss();
                    }
                });
                break;

            case R.id.player_title_circle_img:
                    titleImg.setVisibility(View.VISIBLE);
                    circleTitleImage.setVisibility(View.GONE);

                break;
            case R.id.player_title_img:
                    titleImg.setVisibility(View.GONE);
                    circleTitleImage.setVisibility(View.VISIBLE);
                break;
            //结束activity
            case R.id.player_back:
                    finish();
                break;
            case R.id.player_ll_tab1:

                break;
            case R.id.player_ll_tab2:
                Intent intent = new Intent(this,RecommendActivity.class);
                intent.putExtra("ids",""+intExtra);
                startActivity(intent);
                break;
            case R.id.player_ll_tab3:
                break;
            case R.id.player_ll_tab4:
                showShare();
                break;

        }
    }



    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {

            case ConstantValue.START:
                int currentPosition = this.mediaPlayer.getCurrentPosition();
                seekbar.setMax(this.mediaPlayer.getDuration());
                seekbar.setProgress(currentPosition);
                duration.setText("-"+simpleDateFormat.format(new Date(currentPosition))+"");
                handler.sendEmptyMessageDelayed(ConstantValue.seek_auto_update,1000);
                break;
            case ConstantValue.seek_auto_update:
                int progress = seekbar.getProgress();
                seekbar.setProgress(progress+1000);
                handler.sendEmptyMessageDelayed(ConstantValue.seek_auto_update,1000);
                break;
            case ConstantValue.seek_bar_completion:
                seekbar.setProgress(0);
                handler.removeMessages(ConstantValue.seek_auto_update);
                break;
        }
        return true;
    }



    private class MusicServiceConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            iService = (IService) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        duration.setText("-"+simpleDateFormat.format(new Date(progress))+"");
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
            int progress = seekBar.getProgress();
            iService.callToSeek(progress);

    }

    private void showShare() {
        ShareSDK.initSDK(this);
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();
        // 分享时Notification的图标和文字  2.5.9以后的版本不调用此方法
        //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
        oks.setTitle("心理FM");
        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
        oks.setTitleUrl("http://www.baidu.com");
        // text是分享文本，所有平台都需要这个字段
        oks.setText("心理FM,值得倾听的声音");
        //分享网络图片，新浪微博分享网络图片需要通过审核后申请高级写入接口，否则请注释掉测试新浪微博
        oks.setImageUrl("http://f1.sharesdk.cn/imgs/2014/02/26/owWpLZo_638x960.jpg");
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        //oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl("http://sharesdk.cn");
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment("我是测试评论文本");
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite("ShareSDK");
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl("http://sharesdk.cn");

        // 启动分享GUI
        oks.show(this);
    }

}
